"""
用户接口
"""
# sfb
import json
from fastapi import APIRouter
import uuid

# zjb
from pydantic import BaseModel

from models import User
from schemas import User_Pydantic, UserIn_Pydantic
from core.utils import SelfJSONResponse, SelectJSONResponse, computeMD5

user = APIRouter(tags=["用户相关"], prefix="/userAction")


@user.post("/add", summary="新增用户")
async def add_user(userInfo: UserIn_Pydantic):
    userNew = userInfo.dict()
    userRs = await User.create(
        userid=''.join(str(uuid.uuid4()).split("-")),
        loginname=userNew['loginname'],
        groupid=userNew['groupid'],
        pwd=computeMD5(userNew['pwd']),
        realname=userNew['realname'],
        mobilephone=userNew['mobilephone'],
        sex=userNew['sex'],
        status=userNew['status'],
    )
    return SelfJSONResponse(code=200,
                            data=userRs.getJson(),
                            msg="新增成功！")


@user.delete("/{userid}", summary="删除用户")
async def delete_user(userid: str):
    try:
        await User.filter(userid=userid).delete()
        return SelfJSONResponse(code=200, msg="删除成功！")
    except:
        return SelfJSONResponse(code=500, msg="删除失败！")


@user.put("/profile", summary="修改用户")
async def add_user(userInfo: UserIn_Pydantic):
    userNew = userInfo.dict()
    await User.filter(userid=userNew['userid']).update(
        loginname=userNew['loginname'],
        groupid=userNew['groupid'],
        pwd=computeMD5(userNew['pwd']),
        realname=userNew['realname'],
        mobilephone=userNew['mobilephone'],
        sex=userNew['sex'],
        status=userNew['status']
    )
    return SelfJSONResponse(code=200,
                            msg="修改成功！")


@user.put("/resetPwd", summary="重置密码")
async def reset_pwd(userid: str):
    await User.filter(userid=userid).update(pwd=computeMD5("123456"))
    return SelfJSONResponse(code=200,
                            msg="密码重置成功！")


class UpdatePwdModel(BaseModel):
    newPassword: str
    oldPassword: str
    userid: str


@user.put("/updatePwd", summary="修改密码")
async def update_pwd(updatePwd: UpdatePwdModel):
    rs = await User.filter(userid=updatePwd.userid, pwd=computeMD5(updatePwd.oldPassword)).update(
        pwd=computeMD5(updatePwd.newPassword))
    if rs != 0:
        return SelfJSONResponse(code=200,
                                msg="修改成功！")
    else:
        return SelfJSONResponse(code=500,
                                msg="原密码错误！")

@user.get("/profile", summary="当前用户")
async def get_user(userid: str):
    userInfo = await User.get(userid=userid)
    rs = await User_Pydantic.from_tortoise_orm(userInfo)
    return SelfJSONResponse(code=200, data=rs.dict(), msg="查询成功！")


@user.get("/list", summary="查询列表用户")
async def list_User():
    users = await User.all()
    rs = list()
    for userInfo in users:
        rs.append(userInfo.getJson())

    return SelectJSONResponse(code=200, rows=rs,
                              total=await User.all().count(), msg="查询成功")
